package cn.edu.zjicm.wordsnet_d.activity.base;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.os.Handler;
import android.widget.Toast;
import cn.edu.zjicm.wordsnet_d.activity.GuideActivityFull;
import cn.edu.zjicm.wordsnet_d.activity.LeaderboardActivity;
import cn.edu.zjicm.wordsnet_d.activity.LoginActivity;
import cn.edu.zjicm.wordsnet_d.activity.MainActivity;
import cn.edu.zjicm.wordsnet_d.activity.PersonalAccountActivity;
import cn.edu.zjicm.wordsnet_d.activity.RegisterActivity;
import cn.edu.zjicm.wordsnet_d.activity.SelectBookActivity;
import cn.edu.zjicm.wordsnet_d.activity.WelcomeActivity;
import cn.edu.zjicm.wordsnet_d.data.MobclickAgentData;
import cn.edu.zjicm.wordsnet_d.data.StaticData;
import cn.edu.zjicm.wordsnet_d.datapersistent.AppPreference;
import cn.edu.zjicm.wordsnet_d.synchronize.HeadImageInterface;
import cn.edu.zjicm.wordsnet_d.synchronize.PayInterface;
import cn.edu.zjicm.wordsnet_d.synchronize.PunchInterface;
import cn.edu.zjicm.wordsnet_d.synchronize.UserInterface;
import cn.edu.zjicm.wordsnet_d.util.BitmapUtil;
import cn.edu.zjicm.wordsnet_d.util.LogUtil;
import cn.edu.zjicm.wordsnet_d.util.Utils;

public class LoginWeixinBaseActivity extends WordBaseActivity {
	String weichatHeadimgurl = null;
	boolean hasLoginByWeixin = true; // 是否曾经用此微信账号登陆过
	Bitmap photo = null;

	public void updateUserData(final String code) {
		new Thread() {
			public void run() {
				URL url;
				BufferedReader reader = null;
				String s = "";
				try {
					url = new URL("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + StaticData.APP_ID_WECHAT + "&secret=" + StaticData.APPSECRET_WECHAT + "&code=" + code
							+ "&grant_type=authorization_code");
					URLConnection con = url.openConnection();
					reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
					String line = reader.readLine().toString();
					s += line;
					while ((line = reader.readLine()) != null) {
						s = s + line;
					}
				} catch (MalformedURLException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					if (reader != null) {
						try {
							reader.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
				JSONObject jsonObj;
				String accessToken = "";
				String openId = "";

				try {
					jsonObj = new JSONObject(s);
					accessToken = jsonObj.getString("access_token");
					openId = jsonObj.getString("openid");
				} catch (JSONException e) {
					e.printStackTrace();
				}
				BufferedReader br = null;
				String str = "";
				try {
					URL userUrl = new URL("https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openId);
					URLConnection conn = userUrl.openConnection();
					br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
					String tmpStr = br.readLine();
					str = tmpStr;
					if ((tmpStr = br.readLine()) != null) {
						str += tmpStr;
					}
				} catch (MalformedURLException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}

				try {
					JSONObject jsonUserInfo = new JSONObject(str);
					String weichatOpenID = jsonUserInfo.getString("openid");
					String weichatNickname = Utils.changeCharsetToUTF8(jsonUserInfo.getString("nickname"));
					String weichatUnionid = jsonUserInfo.getString("unionid");
					weichatHeadimgurl = jsonUserInfo.getString("headimgurl");
					if (weichatHeadimgurl.length() > 0)
						photo = Utils.getbitmap(weichatHeadimgurl);
					AppPreference.setLoginID(LoginWeixinBaseActivity.this, weichatNickname);
					AppPreference.setWeChatOpenid(LoginWeixinBaseActivity.this, weichatOpenID);
					AppPreference.setWeChatUnionid(LoginWeixinBaseActivity.this, weichatUnionid);
					AppPreference.setNickName(LoginWeixinBaseActivity.this, weichatNickname);
					toLoginWeixin(weichatUnionid, weichatHeadimgurl, weichatNickname);
					AppPreference.setFirstGuidePage(LoginWeixinBaseActivity.this, false);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			};
		}.start();
	}

	protected void toLoginWeixin(String unionId, String pic, String nickName) {
		loginWeixinHandler.sendMessage(loginWeixinHandler.obtainMessage(UserInterface.MSG_START));
		UserInterface.getInstance(this).loginWeixin(unionId, pic, nickName, loginWeixinHandler);
	}

	private Handler loginWeixinHandler = new Handler() {
		ProgressDialog dialog2 = null;

		public void handleMessage(android.os.Message msg) {
			if (msg.what != UserInterface.MSG_START)
				if (dialog2 != null) {
					dialog2.dismiss();
					dialog2 = null;
				}

			switch (msg.what) {
			case UserInterface.MSG_START:
				dialog2 = ProgressDialog.show(LoginWeixinBaseActivity.this, null, "正在登录...");
				break;
			case UserInterface.MSG_SUCCESS:
				LogUtil.addLog("微信登录成功");
				MobclickAgentData.loginWeixin(LoginWeixinBaseActivity.this, "微信登录成功");
				toSyncAfterWeixinLogin();
				toGetPunch();
				PayInterface.getInstance(LoginWeixinBaseActivity.this).getUserWealth(); // 获取用户财富值
				PayInterface.getInstance(LoginWeixinBaseActivity.this).getUserBought(); // 获取用户购买商品
				hasLoginByWeixin = (Boolean) msg.obj;
				if (hasLoginByWeixin) { // 如果已经用微信账号登陆过，从服务器下载头像
					LogUtil.addLog("login");
					HeadImageInterface.getInstance(LoginWeixinBaseActivity.this).downloadHeadImage();
				} else if (weichatHeadimgurl != null && weichatHeadimgurl.length() > 0) {
					LogUtil.addLog("register:" + weichatHeadimgurl);
					if (photo != null) {
						BitmapUtil.saveHeadPortrait(photo, LoginWeixinBaseActivity.this);
						updateImage(photo);
					} else {
						LogUtil.addLog("photo null");
					}
				}
				break;
			case UserInterface.MSG_INCORRECT_PASSWORD:
				Toast.makeText(LoginWeixinBaseActivity.this, "微信登录失败", Toast.LENGTH_SHORT).show();
				MobclickAgentData.loginWeixin(LoginWeixinBaseActivity.this, "微信登录失败");
				break;
			case UserInterface.MSG_BAD_NETWORK:
				Toast.makeText(LoginWeixinBaseActivity.this, UserInterface.MSG_BAD_NETWORK_STRING, Toast.LENGTH_SHORT).show();
				MobclickAgentData.loginWeixin(LoginWeixinBaseActivity.this, "微信登录失败，未检测到网络连接");
				break;
			case UserInterface.MSG_WEB_SITE_ACCESS_FAILURE:
				Toast.makeText(LoginWeixinBaseActivity.this, UserInterface.MSG_WEB_SITE_ACCESS_FAILURE_STRING, Toast.LENGTH_SHORT).show();
				MobclickAgentData.loginWeixin(LoginWeixinBaseActivity.this, "微信登录失败，连接服务器失败");
				break;
			case UserInterface.MSG_WEB_SITE_ERROR:
				Toast.makeText(LoginWeixinBaseActivity.this, UserInterface.MSG_WEB_SITE_ACCESS_FAILURE_STRING, Toast.LENGTH_SHORT).show();
				MobclickAgentData.loginWeixin(LoginWeixinBaseActivity.this, "微信登录失败，服务器错误");
				break;
			}
		};
	};

	private void updateImage(Bitmap photo) {
		HeadImageInterface.getInstance(LoginWeixinBaseActivity.this).upload(photo, uploadHandler);
	}

	Handler uploadHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {

			switch (msg.what) {
			case UserInterface.MSG_START:
				break;
			case UserInterface.MSG_SUCCESS:
				break;
			case UserInterface.MSG_UNSUCCESS:
				break;
			case UserInterface.MSG_BAD_NETWORK:
				break;
			case UserInterface.MSG_WEB_SITE_ACCESS_FAILURE:
				break;
			case UserInterface.MSG_WRONG_PHOTO:
				break;
			default:
				break;
			}
		};
	};

	protected void toSyncAfterWeixinLogin() {
		syncAfterWeixinLoginHandler.sendMessage(syncAfterWeixinLoginHandler.obtainMessage(UserInterface.MSG_START));
		UserInterface.getInstance(this).sync(syncAfterWeixinLoginHandler);
	}

	Handler syncAfterWeixinLoginHandler = new Handler() {
		ProgressDialog dialog2 = null;

		public void handleMessage(android.os.Message msg) {
			if (msg.what != UserInterface.MSG_START) {
				if (dialog2 != null) {
					dialog2.dismiss();
					dialog2 = null;
				}
			}

			switch (msg.what) {
			case UserInterface.MSG_START:
				LogUtil.addLog("正在同步用户数据");
				dialog2 = ProgressDialog.show(LoginWeixinBaseActivity.this, null, "正在同步用户数据...");
				break;
			case UserInterface.MSG_SUCCESS:
				Toast.makeText(LoginWeixinBaseActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
				MobclickAgentData.loginWeixin(LoginWeixinBaseActivity.this, "微信登录成功，同步成功");
				LogUtil.addLog("同步成功");
				loginWeixinSuccess();
				break;
			case UserInterface.MSG_UNSUCCESS:
				Toast.makeText(LoginWeixinBaseActivity.this, "同步失败", Toast.LENGTH_SHORT).show();
				MobclickAgentData.loginWeixin(LoginWeixinBaseActivity.this, "微信登录失败，同步失败");
				break;
			case UserInterface.MSG_BAD_NETWORK:
				Toast.makeText(LoginWeixinBaseActivity.this, UserInterface.MSG_BAD_NETWORK_STRING, Toast.LENGTH_SHORT).show();
				MobclickAgentData.loginWeixin(LoginWeixinBaseActivity.this, "微信登录失败，同步失败，未检测到网络连接");
				break;
			case UserInterface.MSG_WEB_SITE_ACCESS_FAILURE:
				Toast.makeText(LoginWeixinBaseActivity.this, UserInterface.MSG_WEB_SITE_ACCESS_FAILURE_STRING, Toast.LENGTH_SHORT).show();
				MobclickAgentData.loginWeixin(LoginWeixinBaseActivity.this, "微信登录失败，同步失败，连接服务器失败");
				break;
			default:
				break;
			}
		};
	};

	protected void toGetPunch() {
		getPunchHandler.sendMessage(getPunchHandler.obtainMessage(UserInterface.MSG_START));
		PunchInterface.getInstance(this).getPunch(getPunchHandler);
	}

	Handler getPunchHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			// if (msg.what != RegisterAndLogin.MSG_START)
			switch (msg.what) {
			case UserInterface.MSG_START:
				break;
			case UserInterface.MSG_SUCCESS:
				break;
			case UserInterface.MSG_UNSUCCESS:
				break;
			case UserInterface.MSG_BAD_NETWORK:
				break;
			case UserInterface.MSG_WEB_SITE_ACCESS_FAILURE:
				break;
			default:
				break;
			}
		};
	};

	public void loginWeixinSuccess() {
		if (RegisterActivity.nextOperation == RegisterActivity.TO_MAIN || RegisterActivity.nextOperation == RegisterActivity.TO_PUNCH_OUT) {
			if (hasLoginByWeixin == false)
				PersonalAccountActivity.startActivity(LoginWeixinBaseActivity.this, PersonalAccountActivity.TYPE_REGISTER);
			else if (AppPreference.hasStudyingBook(LoginWeixinBaseActivity.this))
				MainActivity.startActivity(LoginWeixinBaseActivity.this);
			else
				SelectBookActivity.mStartActivity(LoginWeixinBaseActivity.this, StaticData.MODE_INIT);
		} else if (RegisterActivity.nextOperation == RegisterActivity.TO_LEADER_BOARD) {
			LeaderboardActivity.startActivity(LoginWeixinBaseActivity.this);
		}
		if (RegisterActivity.mContext != null) {
			RegisterActivity.mContext.toFinish();
		}
		if (LoginActivity.mLoginActivity != null) {
			LoginActivity.mLoginActivity.toFinish();
		}
		if (GuideActivityFull.mInstance != null) {
			GuideActivityFull.mInstance.toFinish();
		}
	}

}
